using System;
using System.Collections.Generic;

namespace RikMigrations
{
    public class Schema
    {
        public Schema(DbProvider provider)
        {
            Provider = provider;
        }

        public DbProvider Provider { get; set; }

		public virtual void AddSchema()
		{
			var add = Provider.GetAddSchemaCommand();
			add.Execute(Provider);
		}

		public virtual void DropSchema()
		{
			var drop = Provider.GetDropSchemaCommand();
			drop.Execute(Provider);
		}

        public virtual Table AddTable(string name) 
        {
            return new Table(Provider, name, true);
        }

        public virtual Table AddTable(string name, Action<Table> tableAction) 
        {
            Table newTable = new Table(Provider, name, true);
            tableAction.Invoke(newTable);
            return newTable;
        }

        public virtual Table AlterTable(string name) 
        {
            return new Table(Provider, name, false);
        }

        public virtual View AddView(string name, string script) 
        {
            return new View(Provider, name, true, script);
        }

        public void DropTable(string name) 
        {
			var drop = Provider.GetDropTableCommand(name);
			drop.Execute(Provider);
        }

        public void DropView(string name) 
        {
            var drop = Provider.GetDropViewCommand(name);
			drop.Execute(Provider);
        }

        #region Introspection
        public bool TableExists(string name) 
        {
            var command = Provider.GetTableExistsCommand(name);
            command.Execute(Provider);
            return command.Result;
        }

        public bool ViewExists(string name) 
        {
            var command = Provider.GetViewExistsCommand(name);
            command.Execute(Provider);
            return command.Result;
        }

        public bool StoredProcedureExists(string name) 
        {
            var command = Provider.GetStoredProcedureExists(name);
            command.Execute(Provider);
            return command.Result;
        }

        public bool ColumnExists(string tableName, string name) 
        {
            var command = Provider.GetColumnExists(tableName, name);
            command.Execute(Provider);
            return command.Result;
        }

        public List<ForeignKey> FindForeignKeys(Table table) 
        {
            var command = Provider.GetFindForeignKeys(table);
            command.Execute(Provider);
            return command.Result;
        }
        #endregion
    }
}